<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h3 class="page-title">ADE Prompt Debug</h3>
      <p class="page-description">
        Analyze medical progress notes using debuged Prompt with selected LLM.
      </p>
      <div style="text-align: right">
        <el-button
          type="primary"
          icon="el-icon-caret-right"
          @click="analyzePrompts"
          :loading="loading"
        >
          Analyze All
        </el-button>
      </div>
    </div>
    <el-form :model="form" ref="queryForm" size="mini">
      <!-- 第二部分： 輸入Prompt Template， 显示Prompt内容，展示分析结果 -->
      <el-row :gutter="20" class="prompt-container">
        <!-- 第一个Prompt Template 及分析结果 -->
        <el-col :span="8">
          <el-card class="prompt-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span style="font-size: 14px; font-style: bold; font-weight: 600"
                >Prompt One</span
              >
            </div>

            <!-- 选择LLM -->
            <el-row :gutter="5">
              <el-col :span="9">
                <el-form-item prop="llmOne">
                  <el-select
                    v-model="form.llmOne"
                    placeholder="Select LLM Model"
                    clearable
                    class="model-select"
                  >
                    <el-option
                      v-for="dict in dict.type.llm_model"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <!--选择Prompt模板-->
              <el-col :span="9">
                <el-select
                  v-model="prompt.one"
                  placeholder="Select Prompt"
                  clearable
                  @change="(value) => handleChange(value, 'one')"
                  class="prompt-select"
                >
                  <el-option
                    v-for="dict in prompts"
                    :key="dict.id"
                    :label="dict.identifier"
                    :value="dict.id"
                  />
                </el-select>
              </el-col>

              <el-col :span="6">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-caret-right"
                  @click="analyzePrompt('one')"
                  :loading="loading"
                >
                </el-button>
              </el-col>
            </el-row>

            <!-- 输入PromptOne内容，包括system,user -->
            <el-form-item>
              <el-input
                v-model="form.promptOneSystemContent"
                type="textarea"
                :rows="15"
                placeholder="Pls iput System Prompt content..."
                clearable
                class="prompt-content"
              />
            </el-form-item>
            <el-form-item>
              <el-input
                v-model="form.promptOneUserContent"
                type="textarea"
                :rows="5"
                placeholder="Pls input User Prompt content..."
                clearable
                class="prompt-content"
              />
            </el-form-item>

            <!-- 展示Prompt Template One 对应的分析结果 -->
            <el-form-item>
              <el-card class="result-card">
                <pre v-if="result.promptOneResult" class="result-json">{{
                  formatJson(result.promptOneResult)
                }}</pre>
                <div v-else class="no-result">
                  <i class="el-icon-info"></i> No results yet, please select a
                  prompt and submit for analysis
                </div>
              </el-card>
            </el-form-item>
          </el-card>
        </el-col>

        <!-- 第二个Prompt Template 及分析结果 -->
        <el-col :span="8">
          <el-card class="prompt-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span style="font-size: 14px; font-style: bold; font-weight: 600"
                >Prompt Two</span
              >
            </div>

            <!-- 选择LLM  two-->
            <el-row :gutter="5">
              <el-col :span="9">
                <el-form-item prop="llmTwo">
                  <el-select
                    v-model="form.llmTwo"
                    placeholder="Select LLM Model"
                    clearable
                    class="model-select"
                  >
                    <el-option
                      v-for="dict in dict.type.llm_model"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <!--选择Prompt模板-->
              <el-col :span="9">
                <el-select
                  v-model="prompt.two"
                  placeholder="Select Prompt"
                  clearable
                  @change="(value) => handleChange(value, 'two')"
                  class="prompt-select"
                >
                  <el-option
                    v-for="dict in prompts"
                    :key="dict.id"
                    :label="dict.identifier"
                    :value="dict.id"
                  />
                </el-select>
              </el-col>

              <el-col :span="6">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-caret-right"
                  @click="analyzePrompt('two')"
                  :loading="loading"
                >
                </el-button>
              </el-col>
            </el-row>

            <!-- 输入PromptTwo内容，包括system,user -->
            <el-form-item>
              <el-input
                v-model="form.promptTwoSystemContent"
                type="textarea"
                :rows="15"
                placeholder="Pls iput System Prompt content..."
                clearable
                class="prompt-content"
              />
            </el-form-item>
            <el-form-item>
              <el-input
                v-model="form.promptTwoUserContent"
                type="textarea"
                :rows="5"
                placeholder="Pls input User Prompt content..."
                clearable
                class="prompt-content"
              />
            </el-form-item>

            <!-- 展示Prompt Template Two 对应的分析结果 -->

            <el-form-item>
              <el-card class="result-card">
                <pre v-if="result.promptTwoResult" class="result-json">{{
                  formatJson(result.promptTwoResult)
                }}</pre>
                <div v-else class="no-result">
                  <i class="el-icon-info"></i> No results yet, please select a
                  prompt and submit for analysis
                </div>
              </el-card>
            </el-form-item>
          </el-card>
        </el-col>

        <!-- 第三个Prompt Template 及分析结果 -->
        <el-col :span="8">
          <el-card class="prompt-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span style="font-size: 14px; font-style: bold; font-weight: 600"
                >Prompt Three</span
              >
            </div>

            <!-- 选择LLM  Three-->
            <el-row :gutter="5">
              <el-col :span="9">
                <el-form-item prop="llmThree">
                  <el-select
                    v-model="form.llmThree"
                    placeholder="Select LLM Model"
                    clearable
                    class="model-select"
                  >
                    <el-option
                      v-for="dict in dict.type.llm_model"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <!--选择Prompt模板-->
              <el-col :span="9">
                <el-select
                  v-model="prompt.three"
                  placeholder="Select Prompt"
                  clearable
                  @change="(value) => handleChange(value, 'three')"
                  class="prompt-select"
                >
                  <el-option
                    v-for="dict in prompts"
                    :key="dict.id"
                    :label="dict.identifier"
                    :value="dict.id"
                  />
                </el-select>
              </el-col>

              <el-col :span="6">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-caret-right"
                  @click="analyzePrompt('three')"
                  :loading="loading"
                >
                </el-button>
              </el-col>
            </el-row>

            <!-- 输入PromptOne内容，包括system,user -->
            <el-form-item>
              <el-input
                v-model="form.promptThreeSystemContent"
                type="textarea"
                :rows="15"
                placeholder="Pls iput System Prompt content..."
                clearable
                class="prompt-content"
              />
            </el-form-item>
            <el-form-item>
              <el-input
                v-model="form.promptThreeUserContent"
                type="textarea"
                :rows="5"
                placeholder="Pls input User Prompt content..."
                clearable
                class="prompt-content"
              />
            </el-form-item>

            <!-- 展示Prompt Template Three 对应的分析结果 -->
            <el-form-item>
              <el-card class="result-card">
                <pre v-if="result.promptThreeResult" class="result-json">{{
                  formatJson(result.promptThreeResult)
                }}</pre>
                <div v-else class="no-result">
                  <i class="el-icon-info"></i> No results yet, please select a
                  prompt and submit for analysis
                </div>
              </el-card>
            </el-form-item>
          </el-card>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
  
  <script>
import { promptDebug } from "@/api/ade/adeRecognition";
import { listAllPrompt } from "@/api/ade/prompt";

export default {
  name: "PromptDebug",
  dicts: ["llm_model"],
  data() {
    return {
      // 遮罩层
      loading: false,
      prompts: [],
      // 表单参数
      form: {
        content: "",
        llmOne: null,
        llmTwo: null,
        llmThree: null,
        promptOneSystemContent: null,
        promptOneUserContent: null,
        promptTwoSystemContent: null,
        promptTwoUserContent: null,
        promptThreeSystemContent: null,
        promptThreeUserContent: null,
      },
      //
      prompt:{
        one:null,
        two:null,
        three:null,
      },
      result: {
        promptOneResult: null,
        promptTwoResult: null,
        promptThreeResult: null,
      },
    };
  },
  created() {
    // 页面加载时获取所有Prompt
    this.getPrompts();
  },
  methods: {
    // 获取所有的Prompt Template
    getPrompts() {
      this.loading = true;
      var data = {};
      listAllPrompt(data)
        .then((response) => {
          this.prompts = response.data;
          console.log("Prompts fetched successfully:", this.prompts);
        })
        .catch((error) => {
          console.error("Error fetching prompts:", error);
          this.$message.error("获取Prompt模板失败，请重试");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 处理Prompt选择变化
    handleChange(value, para) {
      console.log("Selected Prompt ID:", value, "Parameter:", para);
      // 根据选择的Prompt ID获取对应的内容
      const selectedPrompt = this.prompts.find((prompt) => prompt.id === value);
      if (selectedPrompt) {
        if (para === "one") {
          this.form.promptOneSystemContent = selectedPrompt.systemPrompt;
          this.form.promptOneUserContent = selectedPrompt.userPrompt;
        } else if (para === "two") {
          this.form.promptTwoSystemContent = selectedPrompt.systemPrompt;
          this.form.promptTwoUserContent = selectedPrompt.userPrompt;
        } else if (para === "three") {
          this.form.promptThreeSystemContent = selectedPrompt.systemPrompt;
          this.form.promptThreeUserContent = selectedPrompt.userPrompt;
        }
      }
    },

    // 格式化JSON结果
    formatJson(jsonData) {
      try {
        if (typeof jsonData === "string") {
          return JSON.stringify(JSON.parse(jsonData), null, 2);
        }
        return JSON.stringify(jsonData, null, 2);
      } catch (error) {
        console.error("Failed to format JSON:", error);
        return jsonData;
      }
    },

    analyzePrompt(type) {
      //  let type = 'one';
      console.log("Analyzing prompt of type:", type);
      let data = {};
      if (type == "one") {
        //判断是否选择了大模型
        if (!this.form.llmOne) {
          this.$message.warning("Pls select the LLM!");
          return;
        }
        //判断prompt是否输入
        if (
          !this.form.promptOneSystemContent &&
          !this.form.promptOneUserContent
        ) {
          this.$message.warning(
            "Pls input Prompt One (System or User Prompt content!) "
          );
          return;
        }

        this.result.promptOneResult = null;
        data = {
          systemPrompt: this.form.promptOneSystemContent,
          userPrompt: this.form.promptOneUserContent,
          llmModel: this.form.llmOne,
        };
      }else if(type == 'two'){
        if(!this.form.llmTwo){
          this.$message.warning("Pls select the LLM!");
          return;
        }
        if(!this.form.promptTwoSystemContent && !this.form.promptTwoUserContent){
          this.$message.warning("Pls input Prompt Two (System or User Prompt content!) ");
          return;
        }
        this.result.promptTwoResult = null;
        data = {
          systemPrompt: this.form.promptTwoSystemContent,
          userPrompt: this.form.promptTwoUserContent,
          llmModel: this.form.llmTwo,
        };
      }else if(type == 'three'){
        if(!this.form.llmThree){
          this.$message.warning("Pls select the LLM!");
          return;
        }
        if(!this.form.promptThreeSystemContent && !this.form.promptThreeUserContent){
          this.$message.warning("Pls input Prompt Three (System or User Prompt content!) ");
          return;
        }
        this.result.promptThreeResult = null;
        data = {
          systemPrompt: this.form.promptThreeSystemContent,
          userPrompt: this.form.promptThreeUserContent,
          llmModel: this.form.llmThree,
        };
      }
      this.loading = true;
      promptDebug(data).then((response) => {
        if (type == "one") this.result.promptOneResult = response.data;
        else if (type == "two") this.result.promptTwoResult = response.data;
        else this.result.promptThreeResult = response.data;
      }).catch((error) => {
        console.error("Error analyzing prompt:", error);
        this.$message.error("Error analyzing prompt:", error);
      }).finally(() => {
        this.loading = false;
      });
    },

    // 分析所有选中的Prompt
    analyzePrompts() {
      const selectedLLMs = [
        this.form.llmOne,
        this.form.llmTwo,
        this.form.llmThree,
      ].filter(Boolean);

      if (selectedLLMs.length === 0) {
        this.$message.warning("Pls select at least one LLM!");
        return;
      }

      if (this.form.llmOne) {
        if (
          !this.form.promptOneSystemContent &&
          !this.form.promptOneUserContent
        ) {
          this.$message.warning(
            "Pls input Prompt One (System or User Prompt content!) "
          );
          return;
        }
      }
      if (this.form.llmTwo) {
        if (
          !this.form.promptTwoSystemContent &&
          !this.form.promptTwoUserContent
        ) {
          this.$message.warning(
            "Pls input Prompt Two (System or User Prompt content!) "
          );
          return;
        }
      }
      if (this.form.llmThree) {
        if (
          !this.form.promptThreeSystemContent &&
          !this.form.promptThreeUserContent
        ) {
          this.$message.warning(
            "Pls input Prompt Three (System or User Prompt content!) "
          );
          return;
        }
      }

      this.loading = true;

      // 构建请求数据
      const analysisRequests = selectedLLMs.map((llm) => {
        if (llm == this.form.llmOne) {
          return {
            type: "one",
            systemPrompt: this.form.promptOneSystemContent,
            userPrompt: this.form.promptOneUserContent,
            llmModel: llm,
          };
        }
        if (llm == this.form.llmTwo) {
          return {
            type: "two",
            systemPrompt: this.form.promptTwoSystemContent,
            userPrompt: this.form.promptTwoUserContent,
            llmModel: llm,
          };
        }
        if (llm == this.form.llmThree) {
          return {
            type: "three",
            systemPrompt: this.form.promptThreeSystemContent,
            userPrompt: this.form.promptThreeUserContent,
            llmModel: llm,
          };
        }
      });

      // 清空之前的结果
      this.result = {
        promptOneResult: null,
        promptTwoResult: null,
        promptThreeResult: null,
      };

      // 并行发送分析请求
      const promises = analysisRequests.map((request) => {
        return promptDebug(request).then((response) => {
          // 确定结果对应的Prompt
          let resultKey;
          if (request.type === "one") {
            resultKey = "promptOneResult";
          } else if (request.type === "two") {
            resultKey = "promptTwoResult";
          } else if (request.type === "three") {
            resultKey = "promptThreeResult";
          }

          if (resultKey) {
            this.result[resultKey] = response.data;
          }

          return response;
        });
      });

      // 等待所有请求完成
      Promise.allSettled(promises)
        .then((results) => {
          const successCount = results.filter(
            (r) => r.status === "fulfilled"
          ).length;
          const errorCount = results.length - successCount;

          if (errorCount > 0) {
            this.$message.warning(
              `部分分析请求失败，成功 ${successCount} 个，失败 ${errorCount} 个`
            );
          } else {
            this.$message.success("分析完成");
          }
        })
        .catch((error) => {
          console.error("Error analyzing prompts:", error);
          this.$message.error("分析过程中发生错误，请重试");
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
};
</script>
  
  <style scoped>
.box-card {
  margin-bottom: 10px;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  margin-top: 5px;
  font-size: 22px;
  color: #303133;
  margin-bottom: 0px;
  font-weight: bold;
}

.page-description {
  font-size: 16px;
  color: #606266;
  line-height: 1.5;
}

.form-card {
  margin-bottom: 10px;
  padding: 0px;
}

.content-input {
  width: 100%;
}

.model-select {
  width: 100%;
}

.prompt-container {
  margin-bottom: 20px;
}

.prompt-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.prompt-select {
  width: 100%;
}

.prompt-content {
  width: 100%;
}

.result-card {
  background-color: #f5f7fa;
  min-height: 90px;
  overflow-y: auto;
  padding: 10px;
}

.result-json {
  font-family: Consolas, Monaco, "Andale Mono", monospace;
  font-size: 12px;
  line-height: 18px;
  white-space: pre-wrap;
  word-break: break-all;
  margin: 0;
}

.no-result {
  color: #909399;
  text-align: center;
  padding: 20px 0;
}

.action-buttons {
  text-align: center;
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 10px;
}
</style>